import { type ImgCropOptions, useImgCropContext } from '@/components/img-crop-modal'
import { useDesignStore } from '@/stores'
import { triggerFile } from '@/utils/file'
import { uploadFile, type UploadResult } from '@/utils/upload'
import { type MaybeRefOrGetter, ref, toValue } from 'vue'

interface UseUploadOpts {
  successHandler: (result: UploadResult) => void
  finallyHandler?: () => void
  /**
   * 上传类型
   * @default 'image'
   */
  type?: Parameters<typeof triggerFile>['0']
  /** @default false */
  crop?: boolean
  cropOpts?: MaybeRefOrGetter<Omit<ImgCropOptions, 'img' | 'success'>>
}
export function useUpload(opts: UseUploadOpts) {
  const uploading = ref<boolean>(false)
  const imgCropContext = useImgCropContext()
  async function uploadAction() {
    const designStore = useDesignStore()
    try {
      const [file] = await triggerFile(opts.type || 'image')
      opts.crop ??= false
      if (opts.crop && imgCropContext && imgCropContext.imgCropModalRef.value) {
        imgCropContext.imgCropModalRef.value.openModal({
          img: file,
          success: upload,
          ...toValue(opts.cropOpts),
        })
      }
      else {
        await upload(file)
      }
      async function upload(file: File) {
        uploading.value = true
        designStore.toggleGlobalSpin(true, '上传中...')
        opts.successHandler(await uploadFile(file))
      }
    }
    finally {
      uploading.value = false
      designStore.toggleGlobalSpin(false)
      opts.finallyHandler?.()
    }
  }
  return {
    uploadAction,
    uploading,
  }
}
